package com.hewep.view;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javafx.application.Platform;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import com.hewep.Main;
import com.hewep.kit.ConfigKit;
import com.hewep.view.task.BootAppTask;
import com.hewep.view.task.InvokerService;

public class AppPane extends AnchorPane{
	public String loginUrl = "http://localhost:"+ConfigKit.getInt("local_port", 80)+"/";
	private Main main;
	WebEngine engine;
	@FXML
	private TextArea console;
	@FXML
	private AnchorPane mainContent;
	@FXML
	private Label port;
	private double mouseDragOffsetX = 0;
    private double mouseDragOffsetY = 0;
    
	public AppPane(Main main) {
		this.main = main;
		this.createWebView();
		this.showBootProgress();
		this.initConsole();
	}
	private void createWebView() {
		FXMLLoader fxml = new FXMLLoader(getClass().getResource("res/app.fxml"));
		fxml.setController(this);
		try {
			Parent parent = fxml.load();
			this.getChildren().add((Node)parent);
			port.setText(ConfigKit.getStr("local_port", ""));
			ConsolePrint consolePrint = new ConsolePrint(System.out, console);
			System.setOut(consolePrint);
			System.setErr(consolePrint);
			
			ToolBar toolBar = (ToolBar) parent.lookup("#main-toolbar");
            toolBar.setOnMousePressed(new EventHandler<MouseEvent>() {
                @Override public void handle(MouseEvent event) {
                    mouseDragOffsetX = event.getSceneX();
                    mouseDragOffsetY = event.getSceneY();
                }
            });
            toolBar.setOnMouseDragged(new EventHandler<MouseEvent>() {
                @Override 
                public void handle(MouseEvent event) {
                    main.getStage().setX(event.getScreenX()-mouseDragOffsetX);
                    main.getStage().setY(event.getScreenY()-mouseDragOffsetY);
                }
            });
            
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 控制台添加菜单功能
	 */
	public void initConsole(){
		ContextMenu menu = new ContextMenu();
		MenuItem item0 = new MenuItem("清空");
		MenuItem item1 = new MenuItem("全选");
		MenuItem item2 = new MenuItem("复制");
		item0.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent arg0) {
				// TODO Auto-generated method stub
				console.clear();
			}
		});
		item1.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				// TODO Auto-generated method stub
				console.selectAll();
			}
		});
		item2.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				// TODO Auto-generated method stub
				console.copy();
			}
		});
		menu.getItems().addAll(item0, item1, item2);
		console.setContextMenu(menu);
	}
	public StackPane createProgressPane(){
		StackPane stack = new StackPane();
		Region veil = new Region();
		veil.setStyle("-fx-background-color:#C5C0AB;-fx-opacity:0.5");
		ProgressIndicator progress = new ProgressIndicator();
        progress.setMaxSize(60, 60);
        stack.getChildren().addAll(veil, progress);
		AnchorPane.setTopAnchor(stack, 0.0);
		AnchorPane.setLeftAnchor(stack, 0.0);
		AnchorPane.setRightAnchor(stack, 0.0);
		AnchorPane.setBottomAnchor(stack, 0.0);
		
		return stack;
	}
	public void showBootProgress(){
		StackPane stack = this.createProgressPane();
		InvokerService invoker = new InvokerService();
		invoker.setTask(new BootAppTask(main));
		
		stack.visibleProperty().bind(invoker.runningProperty());
		invoker.start();
		invoker.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
			@Override
			public void handle(WorkerStateEvent arg0) {
				// TODO Auto-generated method stub
				Desktop d = Desktop.getDesktop();
	            URI address;
	             try {
	                 address = new URI(loginUrl);
	                 d.browse(address);
	             } catch (URISyntaxException | IOException e) {
	                 e.printStackTrace();
	             }
			}
		});
		this.getChildren().add(stack);
	}
	
	@FXML
	private void onSet(ActionEvent event){
		final Stage stage = new Stage(StageStyle.TRANSPARENT);
        Group root = new Group();
        Scene scene = new Scene(root, 600, 400, Color.TRANSPARENT);
        stage.setScene(scene);
        stage.centerOnScreen();
        stage.show();


	}
	@FXML
	private void onMin(ActionEvent event){
		main.getStage().setIconified(true);
	}
	@FXML
	private void onClose(ActionEvent event){
		String command = "taskkill /f /im tools.exe";  
		try {
			Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Platform.exit();
	}
}
